function out = GetNAVCOData(Case2Run,LogisticOrNot,LogOrNot,PlotOn,FigureHandle,IncludeNSize,TruncateFirstPM)
% Crunches NAVCO 1.2 data and plots success as a function of peak
% participation

% Sets Default values
if nargin == 0
    Case2Run = 4; % Sets which case to run, 1- All, 2-Nonviolent, 3-Violent, 4-Only Nonviolent
    LogisticOrNot = 1; % 1 is Logistic, 0 is Rolling Average
    LogOrNot = 1; % 1 is Logged Case, 0 is Not
    PlotOn = 1; % Set to 1 to make plots
    FigureHandle = []; %Set to Empty for default plotting figures
    IncludeNSize = 1; % Set to 1 to include subplot of sample size
    TruncateFirstPM = 0;
end

% Read File
[num,txt,raw]=xlsread('Data.xlsx'); %Loads NAVCO 1.2 Data

% Get Pertinent Data from Spreadsheet
% Only Regime Change
RegimeChange = (num(:,13)==1); %Boolean Vector for Regime Change cases
AllDataOrRegimeChange = RegimeChange;
%AllDataOrRegimeChange = true(length(RegimeChange),1); %Turn on if you want all data
PerPop = num(AllDataOrRegimeChange,19)*100; % Percent of Peak Participating
NVorV = num(AllDataOrRegimeChange,[11 12 23]); %Data on Nonviolence / Violence
success = num(AllDataOrRegimeChange,[7:9]); % Data on success, partial, or failure

% Classify by type of Resistance
NVind = NVorV(:,1)==1;
Vind = NVorV(:,2)==1;
NVOnlyind = NVorV(:,1)==1 & NVorV(:,3) == 0;
% Create Variable of Victory Type 0 is failure, 1 Partial, 2 Success
[blah ind] = find(success==1);
SuccessVar = nan(length(success(:,1)),1); SuccessVar(blah) = ind; SuccessVar = SuccessVar*-1+3;

% Down Select to Desired Case
Downselect{1} = true(length(PerPop),1);
Downselect{2} = NVind;
Downselect{3} = Vind;
Downselect{4} = NVOnlyind;
scenario{1} = 'All';
scenario{2} = 'Nonviolent';
scenario{3} = 'Violent';
scenario{4} = 'Fully Nonviolent';

% Run Desired Cases
for ii = 1: length(Case2Run)
    ii = Case2Run(ii);
    
    % Get Data for Desired Case
    PerPopDS = PerPop(Downselect{ii});
    SuccessVarDS = SuccessVar(Downselect{ii});
    [SortPerPopDS IndPerPopDS] = sort(PerPopDS);
    SortSuccessVarDS = SuccessVarDS(IndPerPopDS);
    
    % Plot Individual Outcomes as a function of peak participation
    if PlotOn
        figure(ii)
        subplot(2,1,1)
        plot(SortPerPopDS,SortSuccessVarDS','-x')
        ylim([-.1 2.1])
        %xlim([0 4])
        xlabel('Peak Participation, %')
        ylabel('Win=2,Partial=1,Loss=0')
        title([scenario{ii},' Raw Data'])
        subplot(2,1,2)
        plot(log10(SortPerPopDS),SortSuccessVarDS','-x')
        ylim([-.1 2.1])
        %xlim([0 4])
        xlabel('log')
        xlabel('Peak Participation, logged %')
        ylabel('Win=2,Partial=1,Loss=0')
    end
    
    clear ProtestVector WinsVector WinsVectorLow WinsVectorHigh nsize tvalue StandardError
    xpoints = [-3.5:.5:1.5];
    WinLossInd = (SuccessVarDS==0)|(SuccessVarDS==1)|(SuccessVarDS==2); % Don't Ignore Partials
    %WinLossInd = (SuccessVarDS==0)|(SuccessVarDS==2); % Ignore Partials
    SuccessVarDSWinLoss = SuccessVarDS(WinLossInd);SuccessVarDSWinLoss=(SuccessVarDSWinLoss==2);
    PerPopDSWinLoss = PerPopDS(WinLossInd);
    
    if LogisticOrNot == 0
        %RollingAverage
        MethodString = 'Rolling Average';
        if LogOrNot == 1
            % Log Setup
            xpoints = -3:.5:1.5;
            plusminus = .25;
            SetFigureHandle(FigureHandle,10+ii,PlotOn);
        else
            % NONLog setup
            xpoints = [0:.25:5];
            plusminus = .5;
            SetFigureHandle(FigureHandle,20+ii,PlotOn);
        end
        % Calculate Success for a given participation
        out = GetRollingAverage(PerPopDSWinLoss,SuccessVarDSWinLoss,xpoints,LogOrNot,plusminus,TruncateFirstPM);   
        %Plot
        if IncludeNSize==1
            subplot(2,1,1)
        end
        PlotProbSuccess(out,LogOrNot,scenario{ii},MethodString,PlotOn)
        if IncludeNSize==1
            subplot(2,1,2)
            plot(out.X,out.nsize,'-x')
            xlabel('Peak Participation, %')
            ylabel('Sample Size')
        end
    else
        % Logistic Regression
        MethodString = 'Logistic Regression';
        if LogOrNot == 1
            % Log Setup
            xpoints = -3:.1:2.0;
            SetFigureHandle(FigureHandle,30+ii,PlotOn);
        else
            % NONLog Setup
            xpoints = [0:.25:5];
            SetFigureHandle(FigureHandle,40+ii,PlotOn);
        end
        % Calculate Regression
        out = GetLogisticRegression(PerPopDSWinLoss,SuccessVarDSWinLoss,xpoints,LogOrNot,0);
        % Plot
        PlotProbSuccess(out,LogOrNot,scenario{ii},MethodString,PlotOn)
    end
end
% Ouput Raw Data As Well
out.XRaw = PerPopDSWinLoss;
out.YRaw = SuccessVarDSWinLoss;
end

function PlotProbSuccess(out,LogYes,scenario,MethodString,PlotOn)
% Creates Plot and labels appropriately
if PlotOn
    if LogYes
        LogString = 'Log ';
    else
        LogString = '';
    end
    plot(out.X,out.Y,'-k',out.X,out.CIlow,'k-.',out.X,out.CIhigh,'k-.')
    ylim([-5 105])
    xlim([min(out.X),max(out.X)])
    grid on
    xlabel(['Peak Participation, ',LogString,'%'])
    ylabel('Probability of Victory, (%)')
    legend('Mean','95% Confidence Interval','location','southeast')
    %title([scenario,' Statistics Based on ',LogString,'% Population Using ',MethodString])
end
end

function SetFigureHandle(FigureHandle,AssignedFigure,PlotOn)
% Sets Figure to be used
if PlotOn
    if isempty(FigureHandle)
        figure(AssignedFigure)
    else
        figure(FigureHandle)
    end
end
end
